<?php
namespace Admin\Controller;
use Think\Controller;
use Admin\Common\Api\UserApi;
use Admin\Common\POMVIPClient;
use Admin\Common\POMNetTools;
use Admin\Common\Excel;
class InvoiceController extends BaseController {
    private $adminUser = null;
    public function _initialize(){
    	parent::_initialize();
    	$this->adminUser = new UserApi();

    }

    public function index(){

      $this->display();
    }

   public function InvoiceList(){
          $title =I('request.title','','trim');
        if(!empty($title)){
           $where['order_sn | delivery_sn'] =array('like',"%{$title}%");
           // print_r($_where);exit;
           // $_where['parcelname']=array('like',"%{$keywords}%");
        }

          $consignee =I('request.consignee','','trim');
        if(!empty($consignee)){
           $where['consignee'] =array('like',"%{$consignee}%");
        }
       $tel =I('request.tel','','trim');
        if(!empty($tel)){
           $where['tel'] =array('like',"%{$tel}%");
        }
        $start_time = I('request.start_time','','trim');
        $end_time = I('request.end_time','','trim');

        //如果两个为空，没有条件
        //否则 一个为空，一个有值，两个有值
        if(!(empty($start_time) && empty($end_time))){
            $start_time = empty($start_time)?date("Y-m-d"):$start_time;
            $end_time = empty($end_time)?date("Y-m-d"):$end_time;
            if($start_time>$end_time){
                 $temp=$end_time;
                 $end_time=$start_time;
                 $start_time=$temp;
            }

         $start_time = strtotime($start_time);
         $end_time = strtotime($end_time);
          $where['create_time'] = array(between,array($start_time,$end_time));
           // $str =" and create_time between '".time($start_time)."' and '".time($end_time)."'";
        }
         $where['isbigorder'] = 1;
        $_where_order_field["listrows"] =I("request._listrows");
        $_where_order_field["where"] = $where;
        $_where_order_field["field"] = '*';
        $_where_order_field["order"] = 'create_time desc';
        $_datalist= $this->_getListsFromModel('delivery_info',$_where_order_field);

        foreach ($_datalist['lists'] as $key => $value) {
            $value['new_address'] = "";
            if(!empty($value['country'])){
                $value['new_address'] =$value['country'].'/';
            }
            if(!empty($value['province'])){
                $value['new_address'] .=$value['province'].'/';
            }
            if(!empty($value['city'])){
                $value['new_address'] .=$value['city'].'/';
            }
            if(!empty($value['district'])){
                $value['new_address'] .=$value['district'].'/';
            }
            if(!empty($value['sign_building'])){
                $value['new_address'] .=$value['sign_building'].'</br>';
            }
            if(!empty($value['address'])){
                $value['new_address'] .=$value['address'];
            }

            //配置物流查询url
            $value['logistics_query'] = C('LOGISTICS_QUERY').$value['invoice_no'];
           $_datalist['lists'][$key] = $value;
        }
        $array =array('等待发货单','等待发货','扫描已经发货','取消发货单');
        // print_r($_datalist['page_html']);exit;
        $this->assign('array',$array);
        $this->assign('lists',$_datalist);
        $this->display();
   }




   //出入库详情
public function InvoiceGoodsDetails(){
  $delivery_id = I('request.delivery_id','','trim');
  $this->assign('delivery_id',$delivery_id);
  $this->display('goods_details');

}


public function InvoiceGoodsDetailsList(){
  $delivery_id = I('request.delivery_id','','trim');
  $where['delivery_id'] = $delivery_id;
   $_where_order_field["listrows"] =I("request._listrows");
        $_where_order_field["where"] = $where;
        $_where_order_field["field"] = '*';
        $_where_order_field["order"] = 'id desc';

        $_datalist= $this->_getListsFromModel('delivery_goods',$_where_order_field);
        foreach ($_datalist['lists'] as $key => $value) {
           $sum += $value['send_number'];
        }
        $this->assign('lists',$_datalist);
        $this->assign('sum_number',$sum);

       $this->display('goods_details_list');
}


//物流查询
public function LogisticsQuery(){
   $invoice_no = I('request.invoice_no','','trim');
   $ac = I('request.ac','','trim');
   $arr=array("code"=>$invoice_no,"time"=>time(),"ac"=>$ac);
   $POMVIPClient = new POMVIPClient();
   $a= $POMVIPClient->GetVipInfo();
   $key =$a['KeyCode'];
   $sign=$this->get_sign($arr, $key);
   $data['data']=json_encode(array("data"=>json_encode($arr),"sign"=>$sign,"key"=> $key));
   $ret= POMNetTools::postData(C('LOGISTICS_URL'),$data);
   $jsondata=$ret;
      if(empty($jsondata)){
        $this->error("获取物流信息为空");
      }
      if(!is_array($jsondata)){
        $this->error("获取物流信息失败");
      }
      if($jsondata['error']!="0"){
        $this->error($jsondata['msg']);
      }

      $lst=json_decode( $jsondata['rows'],true);

      $lst[0]['content'] = htmlspecialchars_decode($lst[0]['content']);
      $this->assign("delivery_sn",I('request.delivery_sn','','trim'));
      $this->assign("list",$lst);
      $this->display('logistics_query');
}

function get_sign($data=array(),$key){
   $arr=$data;
   ksort( $arr);
   $str="";
  foreach($arr as $k => $val)
    {
        if(empty($val)) continue;
           $str.=$k.$val;
       }
  $str.=$key;
  $sign=strtoupper(md5($str));
    return $sign;
}




   //导出excel
   public function export_excel(){
          $title =I('request.title','','trim');
        if(!empty($title)){
           $where['order_sn | delivery_sn'] =array('like',"%{$title}%");
           // print_r($_where);exit;
           // $_where['parcelname']=array('like',"%{$keywords}%");
        }

          $consignee =I('request.consignee','','trim');
        if(!empty($consignee)){
           $where['consignee'] =array('like',"%{$consignee}%");
        }
       $tel =I('request.tel','','trim');
        if(!empty($tel)){
           $where['tel'] =array('like',"%{$tel}%");
        }
        $start_time = I('request.start_time','','trim');
        $end_time = I('request.end_time','','trim');

        //如果两个为空，没有条件
        //否则 一个为空，一个有值，两个有值
        if(!(empty($start_time) && empty($end_time))){
            $start_time = empty($start_time)?date("Y-m-d"):$start_time;
            $end_time = empty($end_time)?date("Y-m-d"):$end_time;
            if($start_time>$end_time){
                 $temp=$end_time;
                 $end_time=$start_time;
                 $start_time=$temp;
            }

         $start_time = strtotime($start_time);
         $end_time = strtotime($end_time);
          $where['create_time'] = array(between,array($start_time,$end_time));
           // $str =" and create_time between '".time($start_time)."' and '".time($end_time)."'";
        }
         $where['isbigorder'] = 1;

      $goods_arr = array();
      $list = D('delivery_info')->where($where)->order('delivery_sn desc')->select();
       foreach ($list as $key => $value) {
          $goods_list = D('delivery_goods')->field('a.*,b.goods_cn_name')->alias('a')->join('left join vip_goods as b on a.goods_sn = b.goods_sn')->where('a.delivery_id='.$value['delivery_id'])->select();
                if($goods_list == null){
                  continue;
                }
               $value['new_address'] = "";
                    if(!empty($value['country'])){
                        $value['new_address'] =$value['country'].'/';
                    }
                    if(!empty($value['province'])){
                        $value['new_address'] .=$value['province'].'/';
                    }
                    if(!empty($value['city'])){
                        $value['new_address'] .=$value['city'].'/';
                    }
                    if(!empty($value['district'])){
                        $value['new_address'] .=$value['district'].'/';
                    }
                    if(!empty($value['sign_building'])){
                        $value['new_address'] .=$value['sign_building'].'</br>';
                    }
                    if(!empty($value['address'])){
                        $value['new_address'] .=$value['address'];
                    }

          if(!empty($goods_list )){
            foreach ($goods_list as $k => $v) {
                 $v['delivery_sn'] = $value['delivery_sn'];
                 $v['source_order_sn'] = $value['source_order_sn'];
                 $v['consignee'] = $value['consignee'];
                 $v['mobile'] = $value['mobile'];
                 $v['new_address'] = $value['new_address'];
                 $v['create_time'] = $value['create_time'];
                 $v['expresscompany_name'] = $value['expresscompany_name'];
                 $v['shipping_name'] = $value['shipping_name'];
                 $v['shipping_fee'] = $value['shipping_fee'];
                 $v['status'] = $value['status'];
                 $goods_arr[] =$v;
            }

          }
       }
    // print_r($goods_arr);exit;
     $arr =array('等待发货单','等待发货','扫描已经发货','取消发货单');
    //  $data = array(array('序号','发货单号','订单号','商品名称','商品中文名','商品条形码','商品属性','数量','重量(kg)','电话','地址','快递公司名','快递公司线路','快递费用','状态','采购时间'));
    $data = array();
      foreach ($goods_arr as $key => $value) {
        $array=array();

        array_push($array,$key+1,$value['delivery_sn'],$value['source_order_sn'],$value['goods_name'],$value['goods_cn_name'],$value['barcode'],$value['goods_attr'],$value['send_number'],$value['goods_weight'],$value['mobile'],$value['new_address'],$value['expresscompany_name'],$value['shipping_name'],$value['shipping_fee'],$arr[$value['status']],date('Y-m-d H:i:s',$value['create_time']));
        array_push($data,$array);
      }
       $title = "发货单记录".date('Y-m-d H:i');
      $excel = new Excel();
      // header("Content-type:text/html;charset=UTF-8");
      // $excel->download($data,$title,'');

      $excel->put_csv($data,array('序号','发货单号','订单号','商品名称','商品中文名','商品条形码','商品属性','数量','重量(kg)','电话','地址','快递公司名','快递公司线路','快递费用','状态','采购时间'),$title);
   }
}
